package com.medical.blood.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.blood.entity.DeviceSupplies;
import com.medical.blood.mapper.DeviceSuppliesMapper;
import org.springframework.stereotype.Service;

@Service
public class DeviceSuppliesService extends ServiceImpl<DeviceSuppliesMapper, DeviceSupplies> {

    /**
     * 初始化设备耗材（首次使用时配置阈值）
     * @param supplies 耗材配置（含设备ID、阈值）
     * @return 初始化结果
     */
    public boolean initSupplies(DeviceSupplies supplies) {
        // 校验设备ID是否已存在
        DeviceSupplies exist = lambdaQuery()
                .eq(DeviceSupplies::getDeviceId, supplies.getDeviceId())
                .one();

        if (exist != null) {
            return false; // 已存在则不重复初始化
        }
        return save(supplies);
    }

    /**
     * 更新耗材使用量（采血后调用，减少针头、试管数量）
     * @param deviceId 设备ID
     * @param useNeedle 消耗的针头数量
     * @param useTube 消耗的试管数量
     * @return 更新结果
     */
    public boolean updateSupplies(String deviceId, int useNeedle, int useTube) {
        DeviceSupplies supplies = lambdaQuery()
                .eq(DeviceSupplies::getDeviceId, deviceId)
                .one();

        if (supplies == null) {
            throw new RuntimeException("设备耗材未初始化，请先配置");
        }

        // 更新剩余数量
        supplies.setNeedleCount(supplies.getNeedleCount() - useNeedle);
        supplies.setTubeCount(supplies.getTubeCount() - useTube);

        // 阈值校验：低于阈值则触发预警
        if (supplies.getNeedleCount() <= supplies.getThresholdNeedle()) {
            // 触发预警（示例：调用消息推送服务）
            sendWarning(deviceId, "针头数量不足：剩余" + supplies.getNeedleCount());
        }
        if (supplies.getTubeCount() <= supplies.getThresholdTube()) {
            sendWarning(deviceId, "试管数量不足：剩余" + supplies.getTubeCount());
        }

        return updateById(supplies);
    }

    /**
     * 模拟消息推送（实际需对接短信/企业微信/邮件）
     * @param deviceId 设备ID
     * @param msg 预警内容
     */
    private void sendWarning(String deviceId, String msg) {
        System.out.println("[预警] 设备[" + deviceId + "]：" + msg);
        // 实际实现：调用第三方通知接口（如钉钉机器人、短信API）
    }
}